package com.thh.datamonitor.service.impl;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.thh.common.core.model.entity.SysUser;
import com.thh.common.enums.DatabaseUserStatusEnums;
import com.thh.common.exception.ServiceException;
import com.thh.common.exception.user.NotLoginException;
import com.thh.common.utils.*;
import com.thh.core.manager.DataSourcePoolManager;
import com.thh.datamonitor.config.DataMonitorConfig;
import com.thh.datamonitor.dto.TmdDatabaseDto;
import com.thh.datamonitor.entity.TmdUserDatabase;
import com.thh.datamonitor.executor.AbstractDbExecutor;
import com.thh.datamonitor.executor.DbExecutorFactory;
import com.thh.datamonitor.param.mapper.TmdUserDatabaseMapper;
import com.thh.datamonitor.utils.DadaBaseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.thh.datamonitor.param.mapper.TmdDatabaseMapper;
import com.thh.datamonitor.entity.TmdDatabase;
import com.thh.datamonitor.service.ITmdDatabaseService;
import com.thh.common.core.text.Convert;

/**
 * 数据库配置Service业务层处理
 * 
 * @author thh
 * @date 2022-06-23
 */
@Service
public class TmdDatabaseServiceImpl implements ITmdDatabaseService 
{

    private final static Logger logger = LoggerFactory.getLogger(TmdDatabaseServiceImpl.class);
    @Autowired
    private TmdDatabaseMapper tmdDatabaseMapper;

    @Autowired
    private TmdUserDatabaseMapper tmdUserDatabaseMapper;

    @Autowired
    private DbExecutorFactory dbExecutorFactory;

    @Autowired
    private DataMonitorConfig dataMonitorConfig;

    @Autowired
    private DataSourcePoolManager dataSourcePoolManager;

    /**
     * 查询数据库配置
     * 
     * @param databaseId 数据库配置主键
     * @return 数据库配置
     */
    @Override
    public TmdDatabase selectTmdDatabaseByDatabaseId(Long databaseId)
    {
        return tmdDatabaseMapper.selectTmdDatabaseByDatabaseId(databaseId);
    }

    /**
     * 查询数据库配置列表
     * 
     * @param tmdDatabase 数据库配置
     * @return 数据库配置
     */
    @Override
    public List<TmdDatabase> selectTmdDatabaseList(TmdDatabase tmdDatabase)
    {
        return tmdDatabaseMapper.selectTmdDatabaseList(tmdDatabase);
    }

    /**
     * 新增数据库配置
     * 
     * @param tmdDatabaseDto 数据库配置
     * @return 结果
     */
    @Override
    public int insertTmdDatabase(TmdDatabaseDto tmdDatabaseDto)
    {
        tmdDatabaseDto.setCreateTime(DateUtils.getNowDate());
        tmdDatabaseDto.setCreateBy(ShiroUtils.getLoginName());
        // 密码加密入库
        String databasePasswordShow = tmdDatabaseDto.getDatabasePasswordShow();
        if (StringUtils.isNotBlank(databasePasswordShow)) {
            tmdDatabaseDto.setDatabasePassword(AESUtils.encrypt(databasePasswordShow, dataMonitorConfig.getDatabaseAes()));
        }
        return tmdDatabaseMapper.insert(tmdDatabaseDto);
    }

    /**
     * 修改数据库配置
     * 
     * @param tmdDatabaseDto 数据库配置
     * @return 结果
     */
    @Override
    public int updateTmdDatabase(TmdDatabaseDto tmdDatabaseDto)
    {
        // 密码加密入库
        String databasePasswordShow = tmdDatabaseDto.getDatabasePasswordShow();
        if (StringUtils.isNotBlank(databasePasswordShow)) {
            tmdDatabaseDto.setDatabasePassword(AESUtils.encrypt(databasePasswordShow, dataMonitorConfig.getDatabaseAes()));
        }
        tmdDatabaseDto.setUpdateTime(DateUtils.getNowDate());
        tmdDatabaseDto.setCreateBy(ShiroUtils.getLoginName());
        dataSourcePoolManager.deleteDruidDataSource(tmdDatabaseDto.getDatabaseId());
        return tmdDatabaseMapper.updateById(tmdDatabaseDto);
    }

    /**
     * 批量删除数据库配置
     * 
     * @param databaseIds 需要删除的数据库配置主键
     * @return 结果
     */
    @Override
    public int deleteTmdDatabaseByDatabaseIds(String databaseIds)
    {
        String[] idArr = Convert.toStrArray(databaseIds);
        if (idArr.length > 0) {
            for (String id : idArr) {
                dataSourcePoolManager.deleteDruidDataSource(id);
            }
        }
        return tmdDatabaseMapper.deleteDatabaseByIds(idArr);
    }

    /**
     * 删除数据库配置信息
     * 
     * @param databaseId 数据库配置主键
     * @return 结果
     */
    @Override
    public int deleteTmdDatabaseByDatabaseId(Long databaseId)
    {
        dataSourcePoolManager.deleteDruidDataSource(databaseId);
        return tmdDatabaseMapper.deleteById(databaseId);
    }

    @Override
    public void testConnection(TmdDatabaseDto tmdDatabaseDto) {
        AbstractDbExecutor dbExecutor = dbExecutorFactory.getDbExecutor(tmdDatabaseDto.getDatabaseType());
        try {
            dbExecutor.testConnection(tmdDatabaseDto);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceException("数据库连接失败！errMsg: " + e.getMessage());
        }
    }

    @Override
    public TmdDatabase getMyDatabaseId(String databaseId) {
        SysUser sysUser = ShiroUtils.getSysUser();
        if (sysUser == null) {
            throw new NotLoginException();
        }
        QueryWrapper<TmdUserDatabase> tmdUserDatabaseQueryWrapper = new QueryWrapper<>();
        tmdUserDatabaseQueryWrapper.eq("user_id", sysUser.getLoginName())
                        .eq("database_id", databaseId)
        .eq("status", DatabaseUserStatusEnums.OK.getCode());
        Long count = tmdUserDatabaseMapper.selectCount(tmdUserDatabaseQueryWrapper);
        if (count == 0) {
            throw new ServiceException("您没有该数据库权限！");
        }
        TmdDatabase tmdDatabase = DadaBaseUtils.getDadaBaseCache(databaseId);
        if (StringUtils.isNull(tmdDatabase)) {
            tmdDatabase = tmdDatabaseMapper.selectById(databaseId);
            DadaBaseUtils.setDadaBaseCache(databaseId, tmdDatabase);
        }
        return tmdDatabase;
    }
}
